﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Text.RegularExpressions;

namespace Microsoft.WindowsPhone.ChineseInput.InputProviders
{
    public class SogouCloudInput : CloudInputInterface
    {
        public event EventHandler<CloudInputResponseEventArgs> ResponseReceived;

        public void SendRequest(string text)
        {
            if (!string.IsNullOrEmpty(text))
            {
                WebClient client = new WebClient();
                client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
                client.DownloadStringAsync(
                    new Uri("http://web.pinyin.sogou.com/api/py?key=938cdfe9e1e39f8dd5da428b1a6a69cb&query=" + text));
            }
            else if (ResponseReceived != null)
            {
                ResponseReceived(this, new CloudInputResponseEventArgs() { Candidates = new List<string>() });
            }
        }

        void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            Regex regex = new Regex("ime_callback\\(\"(.+)\",\".+\",.+\\);");
            var matches = regex.Match(e.Result);

            var text = HttpUtility.UrlDecode(matches.Groups[1].Value);

            text = text.Replace("\t", "");

            List<string> candidates = new List<string>();

            foreach (var item in text.Split(' '))
            {
                var pair = item.Split('：');
                candidates.Add(pair[0]);
            }

            if (ResponseReceived != null)
            {
                ResponseReceived(this, new CloudInputResponseEventArgs() { Candidates = candidates });
            }
        }
    }
}
